package cn.jbooter.repository.autoconfigure.first;

import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
import org.springframework.transaction.support.TransactionTemplate;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

import cn.jbooter.repository.autoconfigure.transactional.MultiJDBCTransactionInterceptor;

@Configuration
@AutoConfigureBefore(DruidDataSourceAutoConfigure.class)
@ConditionalOnProperty(prefix="spring.datasource.druid.first",name="enabled",havingValue="true")
@EnableTransactionManagement
public class FirstDataSourceConfigure  {
	private static final Logger logger = LoggerFactory.getLogger(FirstDataSourceConfigure.class);

	/**
	 * 主数据源配置
	 * @return
	 */
	@Primary
	@Bean(initMethod="init",destroyMethod="close")
	@ConfigurationProperties("spring.datasource.druid.first")
	public DataSource firstDataSource(){
		DruidDataSource build = DruidDataSourceBuilder.create().build();
		logger.info("===>>>主数据源初始化完成.");
	    return build;
	}
	
	/**
	 * 主数据源jdbcTemplate配置
	 * @return
	 */
	@Primary
	@Bean
    public JdbcTemplate firstJdbcTemplate(){
        return new JdbcTemplate(firstDataSource());
    }

	/**
     * 使用jdbc编程式事物管理
     * @return
     */
	@Primary
    @Bean
    public TransactionTemplate firstTransactionTemplate(){
        return new TransactionTemplate(txManager());
    }
	
	/**
	 * 主数据源事务配置
	 */
	@Primary
	@Bean
	public PlatformTransactionManager txManager() {
		return new DataSourceTransactionManager(firstDataSource());
	}
	
	/**
	 * 多数据源事物拦截器;
	 * 多数据源的@transcational的事务支持,只能配置在该主数据源配置文件中;
	 * 当且仅当连接多数据源环境才开启!
	 * @param transactionAttributeSource
	 * @return
	 */
	@Primary
	@Bean
	@ConditionalOnProperty(prefix="spring.datasource.druid.second",name="enabled",havingValue="true")
	public MultiJDBCTransactionInterceptor transactionInterceptor(TransactionAttributeSource transactionAttributeSource) {
		MultiJDBCTransactionInterceptor tsi = new MultiJDBCTransactionInterceptor();
		tsi.setTransactionAttributeSource(transactionAttributeSource);
		return tsi;
	}
	
}
